using System;
using GHIElectronics.NETMF.Hardware;
using InternetThermostat.DeviceAccessor;
using InternetThermostat.Models;
using JDI.NETMF.WIZnet;

namespace InternetThermostat
{
    public class WebServices
    {
        HTTPServer httpServer = null;

        public WebServices()
        {
            httpServer = new HTTPServer();
        }

        internal void RegisterEndpoints()
        {
            // TODO: put more endpoints here
            httpServer.RegisterRequestHandler("/", new HTTPServer.HttpRequestHandler(DefaultPageHandler));
            httpServer.RegisterRequestHandler("/temp", new HTTPServer.HttpRequestHandler(TemperaturePageHandler));
            httpServer.RegisterRequestHandler("/debug", new HTTPServer.HttpRequestHandler(DebugPageHandler));


        }

        internal void StartServer()
        {
            httpServer.InitializeServer(AppSettings.HostName, AppSettings.HttpPrefix, AppSettings.HttpPort, AppSettings.MaxPostDataLength);
            httpServer.StartServer();
        }

        internal void StopServer()
        {
            httpServer.StopServer();
        }

        #region Request Handlers


        private static void DefaultPageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e)
        {
            e.ResponseText = "Hello, World!";
        }

        private static void TemperaturePageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e)
        {
            e.ResponseText = "Temperature: " + TemperatureAccessor.GetTemperatureFarenheit().ToString("F3") + "*F";
        }

        private static void DebugPageHandler(string requestURL, HTTPServer.HttpRequestEventArgs e)
        {
            string response = string.Empty;
            response += "DateTime.Now: " + DateTime.Now + "\n";
            response += "RealTimeClock.GetTime(): " + RealTimeClock.GetTime() + "\n";
            response += "Temperature: " + TemperatureAccessor.GetTemperatureFarenheit().ToString("F3") + "*F\n";
            response += "Target Temperature: " + Schedule.TargetTemperature + "\n";

            var nextScheduled = Schedule.GetNextScheduledTemperature();
            var temp = nextScheduled.Value;
            var next = nextScheduled.Key;
            response += "Next Weekly Scheduled Change: " +  (DayOfWeek)next.Day + " " + next.Hour + " " + next.Minute + "\n";
            response += "Next Weekly Scheduled Temperature: " + temp + "\n";

            e.ResponseText = response;
        }

        #endregion


    }
}
